﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace CodeCounsel.SharePoint.NavigationService
{
    public partial class NewApplicationPage : Page
    {
        protected TextBox nameField;

        protected override void OnInit(EventArgs e)
        {
            ((DialogMaster)this.Page.Master).OkButton.Click += OkButton_Click;
            base.OnInit(e);
        }

        void OkButton_Click(object sender, EventArgs e)
        {
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML = "Creating new Navigation Application";
                operation.Begin();
                try
                {
                    NavigationService service = SPFarm.Local.Services.GetValue<NavigationService>();
                    string title = nameField.Text;
                    NavigationApplication application = NavigationApplication.Create(title, service);
                    application.Provision();
                    SPFarm farm = application.Farm;
                    NavigationServiceProxy serviceProxy = (NavigationServiceProxy)farm.GetObject(
                        String.Empty, farm.Id, typeof(NavigationServiceProxy));
                    NavigationApplicationProxy proxy = NavigationApplicationProxy.Create(title, application, serviceProxy, true);
                    proxy.Provision();
                }
                finally
                {
                    operation.EndScript("window.frameElement.commitPopup();");
                }
            }
        }
    }
}
